// pages/addProduct/compileProduct/compipleProduct.js
const utilService = require('../../../utils/utilService.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareMsg:"",
    items: [
      { value: '1', name: '时尚' },
      { value: '2', name: '美妆' },
      { value: '3', name: '母婴' },
      { value: '4', name: '书籍' },
      { value: '5', name: '居家' },
      { value: '6', name: '数码' },
      { value: '-1', name: '其他' },
    ],
    leibie: "选择",       // 类别
    picData:[],       // 服务器图片数组（包含类型）
    myPics: [],      // 图片地址
    picArray: [],    // 图片数组（仅仅图片视频地址  不包含video pic字段）
    picArrays: [], // 仅仅有图片地址没有视频
    myVidios: '',    // 视频地址
    isUploadedVideo: false, // 是否已上传视频
    leibieId: '0',
    priceStr: '0', // 一口果冻价格
    titleStr: '请添加标题',     // 标题
    describeStr: '请添加描述',  // 描述
    id:'996709331451207680', // 商品id
    saleTypeId:1, // 出售方式ID
    saleType:'一口果冻', // 出售方式
    goodsstate:0, // 商品状态标识
    goodsStateStr:'', // 商品状态文字 
    remindStr:'商品上架成功！',
    leftPicCount: 5, //剩余可选照片
    integralAble:true, // 一口价是否可以编辑
    changeImgFlag:0, // 是否是从预览图片返回？修改首图
    goodsData: {},
    bottomTabRight:'保存修改'
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.changeImgFlag == 1){
      if (this.data.isUploadedVideo == true){
        var videoStr = []
        videoStr.push(this.data.myPics[0])
        var videoStr2 = []
        videoStr2.push(this.data.picArray[0])
        var array = []
        for (var index in this.data.picArrays) {
          array.push({ "fileType": 0, "filePath": this.data.picArrays[index] })
        }
        this.setData({
          myPics: videoStr.concat(array),
          picArray: this.data.picArrays.concat(videoStr2)
        })
      }else{
        var array = []
        for (var index in this.data.picArrays) {
          array.push({ "fileType": 0, "filePath": this.data.picArrays[index] })
        }
        this.setData({
          myPics: array,
          picArray: this.data.picArrays
        })
      } 
      this.setData({
        changeImgFlag:0
      })
    }
    console.log(this.data.picArrays)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.setData({
      id: options.id,
    })
    this.getShareMessage(8)
    let param = { "id": this.data.id }
    let leftPicString = ''
    getApp().func.Get(false, getApp().api.goods_details, param,
      function (data) {
        
        that.setData({
          goodsData: data,
          titleStr: data.goodsListEntity.name,
          describeStr: data.description,
          myPics: data.files.filePaths,
          priceStr: data.goodsListEntity.integral,
          leibieId: data.goodsListEntity.goodsTypeId,
          leibie: that.data.items[that.data.leibieId].name,
          saleTypeId: data.goodsListEntity.saleTypeId,
          goodsstate: data.goodsListEntity.status,
          leftPicCount: that.data.leftPicCount - data.files.filePaths.length
        })
        for (var index in that.data.items) {
          if (that.data.items[index].value == that.data.leibieId){
              that.setData({
                leibie: that.data.items[index].name
              })
            }
        }
        if (that.data.saleTypeId == 1) {
          that.setData({
            saleType: '一口果冻',
            integralAble:false
          })
        } else if (that.data.saleTypeId == 3) {
          that.setData({
            saleType: '起拍价',
            integralAble: false
          })
        }

        // 下架时展示
        if (that.data.goodsstate == -1){
          let statustext = '重新上架'
          if (that.data.saleTypeId == 3){
              statustext = '重新竞拍'
          }
            that.setData({
              goodsStateStr: statustext,
              remindStr:'您的商品已成功提交审核，果冻会为您尽快审核。',
              bottomTabRight: that.data.saleTypeId == 3 ? '改为一口果冻' : '保存修改'
            })
        }

        // 上架时、审核中展示
        if (that.data.goodsstate == 2 || that.data.goodsstate == 0){
          that.setData({
            goodsStateStr: '下架不送了',
            remindStr: '商品下架成功！'
          })
        }

        // 审核未通过、商品已赠送展示
        if (that.data.goodsstate == 1 || data.goodsListEntity.count <= 0) {
          that.setData({
            goodsStateStr: '删除',
            remindStr: '删除成功！'
          })
        }
        let Array = []
        let picArrays = [] // 仅仅包含图片地址 没有视频
        for (var index in that.data.myPics) {
          if (that.data.myPics[index].fileType == 1){
            var videoStr = []
            videoStr.push(that.data.myPics[index])
            that.data.myPics.splice(index, 1);
            that.setData({
              isUploadedVideo:true,
              myPics: that.data.myPics.concat(videoStr),
            })
          }
        }
        for (var index in that.data.myPics) {
          if (that.data.myPics[index].fileType == 0) {
            picArrays.push(that.data.myPics[index].filePath)
          }
          Array.push(that.data.myPics[index].filePath) 
        }
        that.setData({
          picArray: Array,
          picArrays: picArrays
        })
        // console.log('+++++++')
        // console.log(that.data.myPics)
        // for (var index in that.data.picArray) {
        //   leftPicString = that.data.picArray[index].slice(-3)
        //   if (leftPicString == 'img'){
        //     that.data.myPics.push({ "type": "img", "src": that.data.picArray[index] })
        //   }else{
        //     that.data.myPics.push({ "type": "video", "src": that.data.picArray[index] })
        //   }
          
        // }
      },
      function (error) {
        wx.showToast({
          title: error.data.message,
          icon: 'none',
          duration: 2000,
        })
      }
    )
  },

  /**
 * 底部左侧按钮点击事件
 */
  soldOut: function (e) {
    let that = this
    var url = ''
    let param=''
    if (this.data.goodsstate == -1) {
      // 下架中展示： 重新上架url
      param = { "goodsId": this.data.id }
      url = getApp().api.goods_dropon
    } else if (this.data.goodsstate == 2 || this.data.goodsstate == 0) { 
      //  上架时、审核中展示:  下架url
      param = { "goodsId": this.data.id }
      url = getApp().api.goods_dropoff
    } else if (this.data.goodsstate == 1 || this.data.goodsData.goodsListEntity.count <= 0) {
      // 已赠送、审核未通过展示:  删除url 
      param = { "id": this.data.id }
      url = getApp().api.goods_del
    }

    getApp().func.Post(false, url, param,
      function (data) {
        console.log(data)
        let title = '提示'
        // 下架成功后  文案显示剩余几次
        if (that.data.goodsstate == 2 || that.data.goodsstate == 0){
          var showMessage = ''
          title = ""
          title = "提示"
          if (data.code == 997 || data.code == 1026 || data.code == -1){
            // 操作频繁和下架次数用完
            showMessage = data.message
          } else if (data.code == 200){
            // 剩余多少次
            showMessage = data.details
          }
          that.setData({
            remindStr: showMessage
          })
        }
        wx.showModal({
          title: title,
          content: that.data.remindStr,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({// 返回首页
                url: '../../home/home'
              })
            }
          }
        })
      },
      function (error) {
        console.log(error)
      })
  },

  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
          self.setData({
            shareMsg: data.title
          })
      },
      function (error) {

      }
    );
  },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    var title = this.data.shareMsg
    var path = "pages/home/home?userId=" + getApp().globalData.userId
    return {
      title: title,
      path: path,
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  },

  uploadPhoto: function (e) {
    // console.log(e.currentTarget.dataset.type)
    let that = this;
    if (that.data.isUploadedVideo == true && that.data.myPics.length >= 6) {
      this.showTost('图片最多上传5张', 'none');
      return
    } else if (that.data.isUploadedVideo == false && that.data.myPics.length >= 5) {
      this.showTost('图片最多上传5张', 'none');
      return
    } else if (that.data.leftPicCount <= 0) {
      this.showTost('图片最多上传5张', 'none');
      return
    }
    // 上传图片
    wx.chooseImage({
      count: that.data.leftPicCount,
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        // console.log(res)
        that.setData({
          leftPicCount: that.data.leftPicCount - tempFilePaths.length
        })
        var array = that.data.myPics
        for (var index in res.tempFilePaths) {
          array.push({ "fileType": 0, "filePath": res.tempFilePaths[index] })
        }

        that.setData({
          myPics: array,
          picArray: that.data.picArray.concat(tempFilePaths),
          picArrays: that.data.picArrays.concat(tempFilePaths),

        })

      },
    });
  },
  addVideoClick: function () {
    var that = this
    let videos = []
    let video = []
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: function (res) {
        videos = [{ fileType: 1, filePath: res.tempFilePath }]
        video = [res.tempFilePath]
        if (that.data.isUploadedVideo) {// 已经上传过视频，直接替换以前的地址
          that.data.myPics[0].filePath = res.tempFilePath
          that.data.picArray[0] = res.tempFilePath
          that.setData({
            myPics: that.data.myPics,
            picArray: that.data.picArray,

          })
        } else {// 没上传过视频，上传新的视频
          that.setData({
            myPics: videos.concat(that.data.myPics),
            picArray: video.concat(that.data.picArray),
            isUploadedVideo: true
          })
        }

      }
    })
  },
  /**
  * 移除图片
  */
  removePhoto: function (e) {
    let idx = e.currentTarget.dataset.idx;
    if (this.data.isUploadedVideo) {
      if (e.currentTarget.dataset.idx == 0) {
        this.setData({ isUploadedVideo: false })
      }
    }
    this.data.myPics.splice(idx, 1);
    this.data.picArray.splice(idx, 1);
    this.data.picArrays.splice(idx, 1);
    this.setData({
      myPics: this.data.myPics,
      picArray: this.data.picArray,
      leftPicCount: this.data.leftPicCount + 1,
      picArrays: this.data.picArrays,
    })
  },
  leibieClick: function (e) {
    wx.navigateTo({
      url: '../classifys/classify?typeID=1' + '&leibieId=' + this.data.leibieId,
    })
  },
  titleInput: function (e) {
    this.setData({ titleStr: e.detail.value })
  },
  describeInput: function (e) {
    this.setData({ describeStr: e.detail.value })
  },
  priceInput: function (e) {
    this.setData({ priceStr: e.detail.value})
  },

  submitForm:function(e){
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 2);
    console.log("formId-2", formId)

  },

/**
 * 点击保存修改
 */
  saveChange:function(e){

    if (this.data.titleStr == '') {
      this.showTost('请添加标题', 'none');
      return
    } else if (this.data.describeStr == '') {
      this.showTost('请添加描述', 'none');
      return
    } else if (this.data.myPics.length == 0 || (this.data.isUploadedVideo == true && this.data.myPics.length == 1)) {
      this.showTost('请添加照片', 'none');
      return
    } else if (this.data.priceStr == ''){
      this.showTost('请填写价格', 'none');
      return
    }

    let files = [];
    let that = this

    getApp().func.UploadFile(that.data.picArray, 0, 0, 0, function (data) {
      let saleType = that.data.saleTypeId
      if (that.data.saleTypeId == 3 && that.data.goodsstate == -1){
         // 如果是竞拍/已下架，为改为一口果冻类型
        saleType = getApp().constant.DEFAULT
      }
      // 上传成功返回url
      files = data;
      let form = new Object();
      form['goodsId'] = that.data.id
      form['title'] = that.data.titleStr
      form['description'] = that.data.describeStr
      form['integral'] = that.data.priceStr
      form['goodsTypeId'] = that.data.leibieId
      form['saleTypeId'] = saleType
      form['urls'] = files;
      console.log('88888')
      console.log(form)
      getApp().func.Post(false, getApp().api.goods_put_updateGoods, form,
        function (data) {
          wx.showModal({
            title: '恭喜您！',
            content: '商品修改成功！',
            showCancel:false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({
                })
              }
            }
          })
        }); 
    },
      function () {
        console.log('bbbb');
      });
  },
  showTost: function (str) {
    wx.showToast({
      title: str,
      icon: 'succes',
      duration: 1000,
      mask: true
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  imgClick: function(){
    console.log(this.data.picArrays)
    wx.navigateTo({
      url: '../previewImg/previewImg?imgUrls=' + encodeURIComponent(JSON.stringify(this.data.picArrays)),
    })
  },

})